/**
 * Created Date: Thursday, November 3rd 2022, 12:28:46 am
 * Author: CodingGorit
 * -----
 * Last Modified: Sat Mar 18 2023
 * Modified By: CodingGorit
 * -----
 * Copyright (c) 2022 fmin-courses
 * ------------------------------------
 * Javascript will save your soul!
 */

const express = require('express');
import { IRouterConf } from "../../../..";
import { Request, Response, NextFunction } from 'express';
import log from "../../../../../utils/log";
import { Result } from "../../../../../common/Result";
import { ResultCodeEnum, ResultMessageEnum } from "../../../../../enums/ResultEmums";
import { IResponse } from "../../../../../types";
import { getRandomVerifyCode } from "../../../../../service/ToolsService";
import { mailApiLimiter } from "../../../../../common/Limiter";
import { sendCustomMessage } from "../../../../../service/MailService";
import MailManager from "../../../../../manager/MailManager";

const tools = express.Router();

// http://localhost:1347/api/private/v1/tools/verifycode
tools.get("/verifycode", function (req: Request, res: IResponse, next: NextFunction) {
    res.sendResult(Result.success<object>(getRandomVerifyCode()));
});

// 获取指定长度的验证码
tools.get("/verifycode/:code", 
    function (req: Request, res: IResponse, next: NextFunction) {
        const code = req.params.code as unknown as number;
        if (code > 0) {
            res.sendResult(Result.success<object>(getRandomVerifyCode(code)));
        } else {
            res.sendResult(Result.paramsError());
        }
    }
);

// 客户端验证, 后端校验账户是否存在,token 校验，authorization 校验
tools.post("/self_services/reset_account",
    mailApiLimiter,
    function (req: Request, res: IResponse, next: NextFunction) {
        const { mail } = req.body;
        if (!mail) {
            res.sendResult(Result.paramsError());
        }
        MailManager.getInstance().sendVerifyCode(["aa@qq.com", "bbb@163.com"],mail, (err: number, reason: string) => {
            if (err) {
                res.sendResult(new Result(ResultCodeEnum.NOTIFY_SUCCESS, ResultMessageEnum.NOTIFY_SUCCESS));
            } else {
                res.sendResult(Result.error(reason));
            }
        });
    }
);

// /api/private/v1/tools/mail-service/custom/mail
tools.post("/mail-service/custom/mail", function(req: Request, res: IResponse, next: NextFunction) {
    const message = req.body;
    sendCustomMessage(message).then(ret => {
        return res.sendResult(ret);
    }).catch(err => {
        return res.sendResult(err)
    })
});


// 错误反馈上报
tools.post("/mini/error/feedback",

    // 插入一条数据
);

const routes: Array<IRouterConf> = [{
    path: "/tools",
    router: tools
}];

export = routes;

